package com.mjk.manager.amis.core.utils;

import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.manager.amis.constans.Constants;
import com.mjk.manager.amis.core.dto.SessionDetails;
import com.mjk.manager.amis.core.model.PlatSys;
import com.mjk.manager.amis.core.model.PlatUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
@Service
@Slf4j
public class SessionHolder {
    @Autowired
    BeeDBService beeDBService;

    public PlatSys getSystem(HttpServletRequest req) {
        SessionDetails session = getSession(req);
        if (null != session) {
            return session.getCurSys();
        }
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
        return (PlatSys) beeDBService.findOneByWrapper(wrapper);
    }

    /**
     * session中设置 应用ID
     *
     * @param request
     * @param syscode
     */
    public void setSystem(HttpServletRequest request, String syscode) {
        SessionDetails session = getSession(request);
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
        wrapper.eq(PlatSys::getCODE, syscode);
        List<PlatSys> sysList = beeDBService.findManyByWrapper(wrapper);
        if (!CollectionUtils.isEmpty(sysList)) {
            session.setCurSys(sysList.get(0));
        }
    }

    /**
     * session中设置用户信息
     *
     * @param request
     * @param user
     */
    public SessionDetails newSession(HttpServletRequest request, PlatUser user) {
        HttpSession session = request.getSession();
        SessionDetails details = getSession(request);
        if (null == details) {
            details = new SessionDetails();
        }
        details.setCurUser(user);
        if (!ObjectUtils.isEmpty(user.getDEF_SYS_ID())) {
            BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
            wrapper.eq(PlatSys::getId, user.getDEF_SYS_ID());
            List<PlatSys> sysList = beeDBService.findManyByWrapper(wrapper);
            if (!CollectionUtils.isEmpty(sysList)) {
                details.setCurSys(sysList.get(0));
            }
        }
        session.setAttribute(Constants.USER_SESSION, details);
        return details;
    }

    /**
     * @param request
     * @return
     */
    public SessionDetails getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        SessionDetails details = (SessionDetails) session.getAttribute(Constants.USER_SESSION);
        return details;
    }

    public void clearSession(HttpServletRequest request) {
        request.getSession().invalidate();
    }
}
